package org.lc.service.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.lc.platform.base.util.SmEncryptUtil;
import org.lc.platform.mybatis.crud.service.impl.CrudBaseServiceImpl;
import org.lc.platform.mybatis.manager.query.QueryBuilder;
import org.lc.service.system.dto.SysLoggerDto;
import org.lc.service.system.entity.SysLogger;
import org.lc.service.system.mapper.SysLoggerMapper;
import org.lc.service.system.service.SysLoggerService;
import org.lc.service.system.vo.SysLoggerVo;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@Service
public class SysLoggerServiceImpl extends CrudBaseServiceImpl<SysLoggerDto, SysLoggerVo, SysLoggerMapper, SysLogger> implements SysLoggerService {

    @Override
    public SysLoggerVo Convertor(SysLogger data) {
        return BeanUtil.copyProperties(data, SysLoggerVo.class);
    }

    @Override
    public QueryBuilder<SysLogger> getQueryBuilder(SysLoggerDto query, QueryBuilder<SysLogger> queryBuilder) {
        queryBuilder.eq(StrUtil.isNotEmpty(query.getCategory()), "category", query.getCategory());
        if (query.getStartTime() != null && query.getStartTime().contains(",")) {
            String[] dates = query.getStartTime().split(",");
            queryBuilder.between("start_time", new Date(Convert.toLong(dates[0])), new Date(Convert.toLong(dates[1])));
        }
        return queryBuilder;
    }

    @Override
    public Map<String, Object> getLogDetail(String log) {
        var logger = this.getById(log);
        var maps = new HashMap<String, Object>();
        if (logger != null) {
            var a = toJSONObject(logger.getQueryParams());
            var b = toJSONObject(logger.getRequestBody());
            var c = toJSONObject(logger.getResponseBody());
            maps.put("queryParams", ObjUtil.isNull(a) ? logger.getQueryParams() : a);
            maps.put("requestBody", ObjUtil.isNull(b) ? logger.getRequestBody() : b);
            maps.put("responseBody", ObjUtil.isNull(c) ? logger.getResponseBody() : c);
            return maps;
        }
        return maps;
    }

    private JSONObject toJSONObject(String message) {
        try {
            var val = SmEncryptUtil.decryptSm4(message);
            return JSONUtil.parseObj(val);
        } catch (Exception ignored) {
        }
        return null;
    }
}